import {useDispatch} from "@/store/index.ts";
import {useLogOut} from "@/hooks/modules/useLogOut.ts";
import {notification} from '@/hooks/modules/useMessage.ts'
import {setUserInfo, setAuthPermission, setAuthRole} from '@/store/modules/user/index.ts'
import {setAuthMenuList} from '@/store/modules/menu/index.ts'
import request from "@/service/request.tsx";

export const usePermissions = () => {
    const dispatch = useDispatch()

    const initPermissions = async (token: string) => {
        if (!token) return
        try {
            const {data: userInfo} = await request.post('/user') as any
            dispatch(setUserInfo(userInfo))
            dispatch(setAuthPermission(userInfo))
            dispatch(setAuthRole(userInfo))

            const {data: menuList} = await request.post('/menus') as any
            dispatch(setAuthMenuList(menuList))

            if (!menuList.length) {
                notification.warning({
                    message: "无权限访问",
                    description: "当前账号无任何菜单权限，请联系系统管理员！"
                });
                useLogOut()
                return Promise.reject("No permission");
            }
        } catch (e) {
            notification.warning({
                message: "无权限访问",
                description: "当前账号获取菜单或角色接口出现异常，请联系系统管理员！"
            });
            useLogOut()
            return Promise.reject("No permission");
        }
    }

    return {initPermissions}
}
